package com.zlzlib.libui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

/**
 * Created by zlz on 2017/10/24.
 */

public abstract class BaseFragment<B extends ViewDataBinding> extends Fragment {

    private View rootView;
    protected B mBinding;
    //是否第一次加载
    private boolean isFirstLoad = true;

    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected void initView() {
    }

    /**
     * 初始化数据 只有第一次可见才加载数据
     */
    protected abstract void initData();

    /**
     * 每次看见就刷新加载数据
     */
    protected void onReData() {
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
            rootView = mBinding.getRoot();
        }
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad) {
            isFirstLoad = false;
            initData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            return;
        }
        //每次看见执行
        onReData();
    }
}
